package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService{

    @Autowired
    private OrderSettingDao orderSettingDao;

    //批量导入预约设置数据
    @Override
    public void add(List<OrderSetting> orderSettings) {
        if(orderSettings == null && orderSettings.size() == 0){
            return;
        }

        for (OrderSetting orderSetting : orderSettings) {
            long countByOrderDate = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
            //判断当前日期是否已经进行了预约设置
            if (countByOrderDate >0){
                //已有设置,进行更新
                orderSettingDao.editNumberByOrderDate(orderSetting);
            }else {
                //没有设置,进行添加
                orderSettingDao.add(orderSetting);
            }
        }
    }

    @Override
    //根据月份查询对应的预约设置数据
    public List<Map> getOrderSettingByMonth(String date) {//格式:yyyy-MM
        String begin=date+"-1";
        String end=date+"-31";
        HashMap<Object,Object> map=new HashMap<>();
        map.put("begin",begin);
        map.put("end",end);
        //调用Dao,根据日期范围查询预约设置数据
        List<OrderSetting> orderSettingByMonth = orderSettingDao.getOrderSettingByMonth(map);

        List<Map> result=new ArrayList<>();
        for (OrderSetting orderSetting : orderSettingByMonth) {
            Map orderSettingMap=new HashMap<>();
            orderSettingMap.put("date",orderSetting.getOrderDate().getDate());//天数,改成date类型
            orderSettingMap.put("number",orderSetting.getNumber());//可预约的人数
            orderSettingMap.put("reservations",orderSetting.getReservations());//已预约的人数
            result.add(orderSettingMap);
        }
        return result;
    }

    @Override
    public void editOrderSettingByDate(OrderSetting orderSetting) {
        long countByOrderDate = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
        if (countByOrderDate >0 ){
            orderSettingDao.editNumberByOrderDate(orderSetting);
        }else {
            orderSettingDao.add(orderSetting);
        }
    }
}
